import base64
def recommend_products(all_products, count=3):
    """按热度推荐模型。"""
    sorted_products = sorted(all_products, key=lambda x: x['popularity'], reverse=True)
    return sorted_products[:count]

def get_all_products(order_by='name', order_dir='asc', mysql=None):
    cursor = mysql.connection.cursor()
    valid_columns = ['name', 'price', 'popularity', 'category', 'stock']
    if order_by not in valid_columns:
        order_by = 'name'
    order_dir = 'asc' if order_dir not in ['asc', 'desc'] else order_dir
    query = f"SELECT id, name, description, price, category, stock, image, popularity FROM products ORDER BY {order_by} {order_dir}"
    cursor.execute(query)
    products = cursor.fetchall()
    cursor.close()
    product_list = [
        {
            'id': p[0], 'name': p[1], 'description': p[2], 'price': p[3],
            'category': p[4], 'stock': p[5], 'image': base64.b64encode(p[6]).decode('utf-8') if p[6] else None, 'popularity': p[7]
        }
        for p in products
    ]
    return product_list

def get_categories(mysql=None):
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT DISTINCT category FROM products")
    categories = cursor.fetchall()
    cursor.close()
    return [category[0] for category in categories]

def get_all_contacts(mysql=None):
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT id, name, email, message, created_at FROM contacts")
    contacts = cursor.fetchall()
    cursor.close()
    return contacts
